package com.logictech.activity.system.interceptors;

import com.logictech.activity.system.entity.Auth;
import com.logictech.activity.system.service.SystemAuthService;
import com.logictech.activity.system.service.SystemUserService;
import com.logictech.activity.system.vo.LoginUser;
import com.logictech.common.util.data.StringUtils;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jeecgframework.p3.core.logger.Logger;
import org.jeecgframework.p3.core.logger.LoggerFactory;
import org.jeecgframework.p3.core.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AuthInterceptor implements HandlerInterceptor {
	public static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

	@Autowired
	private SystemAuthService systemAuthService;
	
	@Autowired
	private SystemUserService systemUserService;

	private List<String> excludeUrls;

	private String mode;

	public List<String> getExcludeUrls() {
		return this.excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	public String getMode() {
		return this.mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
			Exception exception) throws Exception {
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
			ModelAndView modelAndView) throws Exception {
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		if ("DEV".equals(this.mode)) {
			return true;
		}
		String requestPath = getRequestPath(request);
		String basePath = request.getContextPath();
		request.setAttribute("basePath", basePath);
		if (this.excludeUrls.contains(requestPath)) {
			return true;
		}
		if ((requestPath != null) && (requestPath.indexOf(".do") > -1)) {
			if ((requestPath != null) && (requestPath.indexOf("/back/") > -1)) {
				boolean tokenFlag = false;
				String token = request.getParameter("token");
				String userId = request.getParameter("userId");
				if(!StringUtils.isEmpty(token)&&!StringUtils.isEmpty(userId)){
					// 验证token
					LoginUser userDb = this.systemUserService.queryUserByUserId(userId);
					if(userDb == null){
						tokenFlag = false;
					}else{
						if(token.equals(userDb.getToken())){
							tokenFlag = true;
						}else{
							tokenFlag = false;
						}
					}
					
					if (!checkUriAuth(requestPath, userId)) {
						logger.debug("无操作权限！");
						//response.setStatus(401);
						return false;
					}
					
					// token验证通过
					if(tokenFlag){
						LoginUser user = this.systemUserService.queryUserByUserId(userId);
						if(user != null){
							request.getSession().setAttribute("OPERATE_WEB_LOGIN_USER", user);
						}
						return true;
					}
				}
				
				//session验证
				LoginUser user = (LoginUser) request.getSession().getAttribute("OPERATE_WEB_LOGIN_USER");
				if (user == null) {
//					if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ //如果是ajax请求响应头会有，x-requested-with  
//			            response.setHeader("sessionstatus", "timeout");//在响应头设置session状态  
//			        }else{
			        	String url = basePath + "/system/login.do";
			        	response.sendRedirect(url);
//			        }  
					return false;
				}

				if (!checkUriAuth(requestPath, user.getUserId())) {
					logger.debug("无操作权限！");
					if(requestPath.indexOf("/noticeBoard/") > -1){
						response.getWriter().write("无公告栏访问权限！");
					}else{
						response.setStatus(401);
						response.getWriter().write("无操作权限！");
					}
					//response.setStatus(401);
					return false;
				}
				return true;
			}
			return true;
		}

		return true;
	}

	private String getRequestPath(HttpServletRequest request) {
		String requestPath = request.getRequestURI();
		requestPath = requestPath.substring(request.getContextPath().length() + 1);
		return requestPath;
	}

	private boolean checkUriAuth(String requestPath, String userId) {
		requestPath = "/" + requestPath;
		List<Auth> list = this.systemAuthService.queryAuthByAuthContr(requestPath);
		if ((list == null) || (list.size() <= 0)) {
			return true;
		}
		List<Auth> authList = this.systemAuthService.queryAuthByUserIdAndAuthContr(userId, requestPath);
		if ((authList != null) && (authList.size() > 0)) {
			return true;
		}
		return false;
	}
}

